package fr.inserm.umr915.vcfserver.j2ee;



import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;



import fr.inserm.umr915.vcfserver.bio.berkeley.Storage;


public class BerkeleyDBContext implements ServletContextListener
	{
	public BerkeleyDBContext()
		{
		
		}
	
	@Override
	public void contextInitialized(ServletContextEvent ctx)
		{
		WebApplicationContext factory = WebApplicationContextUtils.getRequiredWebApplicationContext(ctx.getServletContext());
		
		try {
			Storage storage=new Storage();
			storage.open(factory,true);
			storage.reloadMetaData();
			ctx.getServletContext().setAttribute("berkeley.db.environment", storage);
			}
		catch (Exception e)
			{
			e.printStackTrace();
			ctx.getServletContext().log(e.getMessage());
			throw new RuntimeException(e);
			}
		}
	

	@Override
	public void contextDestroyed(ServletContextEvent ctx)
		{
		try {	
			Storage storage=(Storage)ctx.getServletContext().getAttribute("berkeley.db.environment");
			if(storage!=null)
				{
				storage.close();
				}
			ctx.getServletContext().removeAttribute("berkeley.db.environment");
			}
		catch (Exception e)
			{
			e.printStackTrace();
			}
		}
	}
